package com.sbl.bajw.pc.service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.fileupload.FileItem;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sbl.bajw.common.MyBatisDao;
import com.sbl.bajw.common.web.MessageException;
import com.sbl.bajw.common.web.RequestUnit;
import com.sbl.bajw.common.web.SessionUnit;
import com.sbl.bajw.common.web.WebContext;
import com.sbl.bajw.mapper.AdvertisingModelDao;
import com.sbl.bajw.pc.model.AdvertisingModel;
import com.sbl.bajw.util.FileUpload;
import com.sbl.bajw.util.LogUtil;

@Service
public class AdvertisingModelService {

	@Resource
	private AdvertisingModelDao dao;
	
	@Resource
	private MyBatisDao gridDao;
	
	static Logger log;
	
	static{
		log = LogUtil.getLogger("Advertising");
	}
	
	@Transactional(readOnly = false)
	public void insert(AdvertisingModel model) throws MessageException{
		try {
			log.info(model.getCreatedBy() + "上传图片");
			uploadFile(model);
			log.info("图片上传成功，属性上传开始：");
			dao.insert(model);
			log.info("属性上传成功。");
		} catch (Exception e) {
			log.info(e);
			e.printStackTrace();
			throw new MessageException("上传异常", "3");
		}
	}
	
	public void update(AdvertisingModel model){
		dao.update(model);
	}
	
	public List<HashMap<String, Object>> getAdvertisingApp(){
		List<HashMap<String, Object>> list = dao.getAdvertisingApp();
		return list;
	}
	
	public String getAdvertisingList(){
		String json = gridDao.selectPage(AdvertisingModelDao.class, null, "getAdvertisingList");
		return json;
	}
	
	public String uploadFile(AdvertisingModel model) throws Exception {
		String id = dao.getAdvertisingId();

		if (id == null || id.equals("")) {
			throw new MessageException("ID不能为空", "2");
		}
		
		String resultPath = "";
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmssS");
		
		FileItem item = RequestUnit.getFileItem("adv");
		if (item != null) {
			String path = WebContext.getRequest().getSession()
					.getServletContext().getInitParameter("UploadPath");
			String dataStr = sf.format(Calendar.getInstance().getTime());
			resultPath = "images/upload/adver/" + FileUpload.saveFile(item, path + "/images/upload/adver/", dataStr + "_img_" + id);
			log.info(SessionUnit.getSessionId() + "图片上传成功:" + resultPath);
			HashMap<String, String> parm = new HashMap<String, String>();
			parm.put("path", resultPath);
			parm.put("groupid", id);
			parm.put("businessType", "4");
			parm.put("filetype", "img");
			dao.insertAttfile(parm);
			model.setPicfileid(id);
			model.setStatus("1");
		} else {
			log.info(SessionUnit.getSessionId() + "没有图片数据");
		}
		
		return resultPath;
	}
}
